<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\index\service;

use app\index\model\Commodity;
use app\index\model\IntegralGoods;
use app\index\model\OrderCommodityAttach;
use app\index\model\OrderEvaluate;
use app\index\model\PresellCommodity;
use app\index\model\Seckill;
use app\index\model\SeckillCommodity;
use app\index\model\SeckillCommoditySku;
use app\index\model\User;
use app\index\util\OrderCount;
use app\shop_admin\model\AttachValue;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\HttpException;
use app\index\model\Configuration;

class CommodityService
{
    private $mid;

    public function __construct()
    {
        global $mid;
        $this->mid = $mid;
    }

    public function findByIds($ids)
    {
        $list = Commodity::where(['id' => $ids])
            ->field([
                'id',
                'merchant_id',
                'type',
                'name',
                'subtitle',
                'label',
                'master',
                'classify_value',
                'original_price',
                'sell_price',
                'min_price',
                'max_price'
            ])
            ->select();
        return [HTTP_SUCCESS, $list];
    }

    public function goodsList(array $data)
    {
        global $user;
        $query = Commodity::where($this->setWhere($data))
            ->field('type,name as goods_name,subtitle,label,master,classify_id,id,
           total,is_original_price,original_price,sell_price,min_price,max_price,sort,is_virtual,virtual_sell,sell,level_price')

            ;
        if (!empty($data['classify_id'])){
            if(strpos($data['classify_id'],"->")!==false){
                $where[] = ['classify_id', 'like', "%" . $data['classify_id'] . "%"];
                $query->where($where);
            }else{
                $where = [
                    ['classify_id', '=', $data['classify_id']],
                    ['classify_id', 'like', $data['classify_id'] . ',%'],
                    ['classify_id', 'like', $data['classify_id'] . '->%'],
                    ['classify_id', 'like', '%->'.$data['classify_id']],
                    ['classify_id', 'like', '%,'.$data['classify_id']],
                    ['classify_id', 'like', '%,'.$data['classify_id'].',%'], #中部条件
                    ['classify_id', 'like', '%->'.$data['classify_id'].'->%'],
                    ['classify_id', 'like', '%->'.$data['classify_id'].',%'],
                ];
                $query->where(function($query1) use ($where){
                    $query1->whereOr($where);
                });
            }
        }
        $res=$query->with(['sku', 'sku.skuInventory', 'classify'])
            ->order('sort DESC,fraction DESC,sell DESC,create_time DESC')
            ->append(['now_level_price'])
            ->paginate(['page' => $data['page'], 'list_rows' => $data['size']])->toArray();
        $data = $res['data'];
        if (!empty($user['level'])) {
            foreach ($data AS $key => $value) {
                if (!empty($value['now_level_price'])) continue;
                $min = null;
                foreach ($value['sku'] AS $index => $item){
                    $array = $item['skuInventory'];
                    if(empty($array['now_level_price']))continue;
                    if (empty($min))
                        $min = $array['now_level_price'];
                    else
                        $min > $array['now_level_price'] && $min = $array['now_level_price'];
                }
                $data[$key]['now_level_price'] = $min;
            }
            $res['data'] = $data;
        }
        return [HTTP_SUCCESS, $res];
    }


    public function goodsInfo(int $id)
    {

        $goods = Commodity::find($id);
        if (!$goods['status']) throw new HttpException(HTTP_UNPROCES, "商品已下架");
        $commodity = Commodity::where('id', $id)->where('mall_id', $this->mid);
        $withs=[];
        if (empty($goods->has_sku)) {
            $withs=array_merge($withs, [
                'merchant', 'ft',
            ]);
        }
        elseif (!empty($goods->has_sku)) {
            $withs=array_merge($withs, ['sku' => function ($query) {
                $query->alias('a')
                    ->join('sku_inventory s', 'a.id=s.sku_id', 'LEFT')
                    ->field('a.*,s.*,(s.total-s.sell) as total')
                    ->append(['now_level_price']);
            }, 'merchant', 'ft']);
        }
        if($commodity && checkAddons(23)){
            $withs=array_merge($withs,['form_template']);
        }

        $commodity->with($withs);

        $res = $commodity->hidden(['delete_time'])->find()->toArray();
        $res['count'] = Commodity::where(['merchant_id' => $goods['merchant_id'], 'status' => 1, 'mall_id' => $this->mid])->count();
        if (!empty($res['is_limitation'])) {//是否限购
            $order = new OrderCount();
            $res['limitation_count'] = $order->commodityByOrderCount($id);
        }
        $res['attach_value'] = json_decode($res['attach_value'], true);
        if (!empty($res['attach_value'])) {
            $atr = $res['attach_value'];
            $atrArr = [];
            foreach ($atr as $k => $v) {
                $av = [];
                foreach ($v['attrValue'] as $ka => $kv) {
                    $atr = AttachValue::find($kv[0]);
                    $sellAtr = OrderCommodityAttach::where([
                        'attach_id' => $kv[0],
                        'status' => 1,
                    ])->sum('num');
                    array_push($av, array_merge($kv, [$atr['stock'] - $sellAtr]));
                }
                $v['attrValue'] = $av;
                array_push($atrArr, $v);
            }
            $res['attach_value'] = $atrArr;
        }
        if (empty($res['form_template'])){
            $res['form_open']=0;
        }

        // 拼团
        if (checkAddons(24)) {
            $res['group'] = Commodity::isGroup($id)[0];
            $res['collage'] = Commodity::isGroup($id)[1];
        }
        // 秒杀
        if (checkAddons(25)) {
            $res['seckill'] = Commodity::isSeckill($id);
        }
        // 预售
        if (checkAddons(34)) {
            $res['presell'] = Commodity::isPresell($id);
        }

        return [HTTP_SUCCESS, $res];
    }


    public function evaluate(array $data)
    {

        $res = OrderEvaluate::where(['a.state' => 2, 'a.commodity_id' => $data['id']])
            ->alias('a')
            ->where('a.mall_id', $this->mid)
            ->join('sku s', 'a.sku=s.id', 'LEFT')
            ->with(['user'])
            ->field('a.user_id,a.content,a.img_url,a.score,a.reply,a.create_time,a.id,a.commodity_id,s.pvs_value')
            ->paginate(['page' => $data['page'], 'list_rows' => $data['size']]);
        return [HTTP_SUCCESS, $res];
    }


    private function setWhere(array $data)
    {
        $where[] = ['status', '=', 1];
        $where[] = ['mall_id', '=', $this->mid];


//        !empty($data['classify_id']) && $where[] = ['classify_id', 'like', "%" . $data['classify_id'] . "%"];

        !empty($data['name']) && $where[] = ['name', 'like', "%" . $data['name'] . '%'];
        !empty($data['merchant_id']) && $where[] = ['merchant_id', '=', $data['merchant_id']];
        return $where;
    }

    private function serOrderBy(array $data)
    {
        if (array_key_exists('price_sort', $data) && !empty($data['price_sort'] == 1)) $order[] = 'sell_price desc';//降序
        if (array_key_exists('price_sort', $data) && !empty($data['price_sort'] == 2)) $order[] = 'sell_price asc';//升序
        if (array_key_exists('sell_sort', $data) && !empty($data['sell_sort'] == 1)) $order[] = 'sell desc';//降序
        if (array_key_exists('sell_sort', $data) && !empty($data['sell_sort'] == 2)) $order[] = 'sell asc';//升序
        return empty($order) ? 'sort desc' : $order;
    }


    public function inventory($commodityId)
    {
        $inventoryService = new InventoryService($commodityId);
        $allInventory = $inventoryService->getAllInventory();
        return [HTTP_SUCCESS, $allInventory];
    }


    public function getManyGoods(array $data, $type)
    {
        $data=array_filter($data,function($v){
            if(!empty($v)) return true;
        });
        if (empty($data))  return [HTTP_SUCCESS, []];

        if ($type == 1) {

            $res = Commodity::where('id', 'in', $data)
                ->with(['sku', 'sku.skuInventory'])
                ->field('id,type,name as goods_name,subtitle,master,classify_id,id,has_sku,total,is_original_price,original_price,
                           sell_price,min_price,max_price,sort,is_virtual,sell,virtual_sell,level_price')
                ->append(['now_level_price'])
                ->orderRaw("field(id,".implode(",", $data).")")
                ->select();
            foreach ($res as $key => $value) {
                // 秒杀
                $res[$key]['seckill'] = Commodity::isSeckill($value['id']);
                // 预售
                $res[$key]['presell'] = Commodity::isPresell($value['id']);
            }
        } else {
            $res = IntegralGoods::where('id', 'in', $data)
                ->with(['sku', 'sku.skuInventory'])
                ->field('type,name as goods_name,subtitle,master,classify_id,id,has_sku,total,
                           sell_price,min_price,max_price,sort,sell')
                ->append(['now_level_price'])
                ->orderRaw("field(id,".implode(",", $data).")")
                ->select();

        }
        return [HTTP_SUCCESS, $res];
    }
}